package org.changs.launcher.device;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.RemoteCallbackList;
import android.os.RemoteException;
import android.widget.Toast;

import org.changs.aplug.ActivityManager;
import org.changs.aplug.interf.IService;
import org.changs.launcher.service.RemoteActivity;
import org.changs.s3.common.RemoteManager;
import org.changs.s3.common.aidl.DeviceScanCallback;
import org.changs.s3.common.aidl.IDeviceScan;

import javax.inject.Inject;

/**
 * Created by yincs on 2017/9/15.
 */

public class DeviceController implements IService, IDeviceScan {
    private static final String SPRS_FIRET = "devicecontroller.sprs_first";
    private final RemoteCallbackList<DeviceScanCallback> mCallbackList = new RemoteCallbackList<>();
    private final Context mContext;
//    private View mQRcodeView;

    private final ConnectWifiOpt mConnectWifiOpt;
    private final ConnectServletOpt mConnectServletOpt;
    private final SharedPreferences mSharedPreferences;


    @Inject
    public DeviceController(Context context, ConnectWifiOpt connectWifiOpt, ConnectServletOpt connectServletOpt, SharedPreferences mSharedPreferences) {
        this.mContext = context;
        this.mConnectWifiOpt = connectWifiOpt;
        this.mConnectServletOpt = connectServletOpt;
        this.mSharedPreferences = mSharedPreferences;

        this.mConnectWifiOpt.setConnectedAction(connect -> {
            if (connect) {
                mConnectServletOpt.run();
            } else {
                mConnectWifiOpt.run();
            }
        });
        this.mConnectServletOpt.setConnectedAction(connect -> {
            if (connect) {
                mSharedPreferences.edit().putBoolean(SPRS_FIRET, true).apply();
                hideQRcode();
                final Intent intent = new Intent(RemoteManager.ACTION_DEVICE_CONNECTED);
                intent.putExtra(RemoteManager.EXTRA_DEVICE_IP, mConnectServletOpt.getNetworkDevice().getIp());
                mContext.sendBroadcast(intent);
            } else {
                mConnectWifiOpt.run();
                mContext.sendBroadcast(new Intent(RemoteManager.ACTION_DEVICE_DISCONNECT));
            }
        });
    }

    @Override
    public void onCreate() {
        mContext.sendBroadcast(new Intent(RemoteManager.ACTION_SERVICE_CREATE));

        mConnectWifiOpt.register(mContext);
        mConnectWifiOpt.run();
        showQRcodeView();
    }

    @Override
    public void onStartCommand(Intent intent, int flags, int startId) {

    }

    @Override
    public void onDestroy() {
        mCallbackList.kill();
        mConnectWifiOpt.unregister(mContext);
    }

    private void hideQRcode() {
        ActivityManager.getInstance().finishActivity(RemoteActivity.class);
//        if (mQRcodeView == null || mQRcodeView.getParent() == null) return;
//        WindowManager manager = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
//        try {
//            manager.removeView(mQRcodeView);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
    }

    private void showQRcodeView() {
        if (mSharedPreferences.getBoolean(SPRS_FIRET, false)) return;
        Intent intent = new Intent(mContext, RemoteActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(RemoteActivity.ACTION_SHOW_QRCODE);
        intent.setData(Uri.parse(DeviceConnectUtils.genDeviceApJsonObject(mContext).toString()));
        mContext.startActivity(intent);
//        if (true)return;
//
//        if (mQRcodeView == null) {
//            mQRcodeView = LayoutInflater.from(mContext).inflate(R.layout.qr_code_layout, null);
//            WindowManager.LayoutParams params = new WindowManager.LayoutParams();
//            params.type = WindowManager.LayoutParams.TYPE_TOAST;
//            params.format = PixelFormat.RGBA_8888;
//            mQRcodeView.setLayoutParams(params);
//            ImageView image = (ImageView) mQRcodeView.findViewById(R.id.image);
//            JsonObject jsonObject = new JsonObject();
//            jsonObject.addProperty("name", mConnectWifiOpt.substringAndroidID(-1));
//            jsonObject.addProperty("ssid", mConnectWifiOpt.getSSID());
//            jsonObject.addProperty("pwd", mConnectWifiOpt.getPwd());
//            final Bitmap qrCode = QRcodeUtils.createQRCode(jsonObject.toString(), (int) mContext.getResources().getDimension(R.dimen.PX549));
//            image.setImageBitmap(qrCode);
//            mQRcodeView.setOnClickListener(v -> toast("长按可隐藏二维码"));
//            mQRcodeView.setOnLongClickListener(v -> {
//                hideQRcode();
//                return true;
//            });
//        }
//        if (mQRcodeView.getParent() == null) {
//            WindowManager manager = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
//            try {
//                manager.addView(mQRcodeView, mQRcodeView.getLayoutParams());
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }
    }

    private void toast(String msg) {
        Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show();
    }


    @Override
    public String getRemoteIp(boolean show) {
        if (mConnectServletOpt.getNetworkDevice() == null) {
            if (show) {
                showQRcodeView();
            }
            return null;
        }
        return mConnectServletOpt.getNetworkDevice().getIp();
    }

    @Override
    public boolean isScanning() {
        return false;
    }

    @Override
    public boolean startScan() {
        mConnectServletOpt.run();
        return true;
    }


    @Override
    public void registerCallback(DeviceScanCallback callback) {
        if (callback != null) {
            mCallbackList.register(callback);
        }
    }

    @Override
    public void unregisterCallback(DeviceScanCallback callback) {
        if (callback != null) {
            mCallbackList.unregister(callback);
        }
    }


    private void notifyCompleteScan() {
        int N = mCallbackList.beginBroadcast();
        try {
            for (int i = 0; i < N; i++) {
                mCallbackList.getBroadcastItem(i).completeScan();
            }
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        mCallbackList.finishBroadcast();
    }

    private void notifyDisconnect() {
        int N = mCallbackList.beginBroadcast();
        try {
            for (int i = 0; i < N; i++) {
                mCallbackList.getBroadcastItem(i).disconnect();
            }
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        mCallbackList.finishBroadcast();
    }
}
